package com.rzico.sbl.ui.manager

import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.isVisible
import androidx.core.widget.TextViewCompat
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityCouponBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.CouponData
import com.rzico.sbl.viewmodel.CouponViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.bottomHide
import com.xinnuo.common.helper.bottomShow
import com.xinnuo.common.helper.dp2px
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.utils.addOnScrollChanged
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.labelview.LabelView
import com.xinnuo.slimadapter.SlimAdapter

class CouponActivity : BaseActivity(R.layout.activity_coupon) {

    private val mBinding by lazy { ActivityCouponBinding.bind(getRootView()) }

    override fun getViewModel() = get<CouponViewModel>()

    override fun initData() {
        initTitle(title = "优惠券")

        initLayout()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding.listLayout.apply {
            emptyLayout.also {
                it.emptyHint.text = "暂无相关优惠券信息！"
            }

            recycleList.also { view ->
                view.loadLinear(
                    refresh = swipeRefresh,
                    onRefresh = { getData(0) },
                    onLoad = {
                        if (!isLoadingMore) {
                            isLoadingMore = true
                            getData(pageNum)
                        }
                    }
                )

                view.addItemDecoration(SpaceTBDecoration(bottom = 60f))
                view.addOnScrollChanged(
                    onShow = { mBinding.couponBottom.bottomShow() },
                    onHide = { mBinding.couponBottom.bottomHide(55f) }
                )

                mAdapter = SlimAdapter.creator()
                    .register<CouponData>(R.layout.item_coupon_list) { jector, bean, index ->
                        jector.apply {
                            text(
                                R.id.item_coupon_count,
                                bean.amount.trimEnd('元', '折')
                            )
                            text(
                                R.id.item_coupon_title,
                                "${
                                    when (bean.scope) {
                                        "all" -> "全场"
                                        "shop" -> "店内"
                                        "mall" -> "商城"
                                        else -> ""
                                    }
                                }${
                                    when (bean.type) {
                                        "fullcut" -> "满减优惠券"
                                        "discount" -> "满折优惠券"
                                        "product" -> "商品券"
                                        else -> ""
                                    }
                                }"
                            )
                            text(
                                R.id.item_coupon_type,
                                "满${bean.minimumPrice.formatDecimalWhenHave()}元可用"
                            )
                            text(
                                R.id.item_coupon_range,
                                "有效期：${
                                    bean.beginDate.getTimeString("yyyy.MM.dd")
                                } ~ ${
                                    bean.endDate.getTimeString("yyyy.MM.dd")
                                }"
                            )

                            visibility(
                                R.id.item_coupon_hint1,
                                visibleValue { bean.type == "fullcut" }
                            )
                            visibility(
                                R.id.item_coupon_hint2,
                                visibleValue { bean.type == "discount" }
                            )

                            with<LabelView>(R.id.item_coupon_label) {
                                it.text = "剩余：${bean.stock}"
                            }

                            with<ConstraintLayout>(R.id.item_coupon) {
                                when (bean.type) {
                                    "fullcut" -> it.setBackgroundResource(R.mipmap.icon_manager17)
                                    "discount" -> it.setBackgroundResource(R.mipmap.icon_manager18)
                                    "product" -> it.setBackgroundResource(R.mipmap.icon_manager19)
                                }
                            }

                            clicked {
                                startActivityEx<CouponDetailActivity>(
                                    "itemId" to bean.id
                                )
                            }

                            longClicked {
                                deleteCoupon(bean.id, index)
                                true
                            }
                        }
                    }
                    .attachTo(view)
                    .addHeader(
                        TextView(getIContext()).apply {
                            text = "温馨提示：长按可删除优惠券"
                            setPadding(dp2px(15f), 0, 0, 0)
                            TextViewCompat.setTextAppearance(this, R.style.Font13_gray)
                        }
                    )
            }
        }
    }

    override fun initListener() {
        mBinding.btAdd.oneClick {
            startActivityEx<CouponAddActivity>(
                "status" to "list"
            )
        }

        observe<String>("couponList") { updateList() }
    }

    /**
     * 删除优惠券
     */
    private fun deleteCoupon(itemId: String, index: Int) {
        showHintDialog(
            title = "优惠券",
            hint = "确定要删除该优惠券吗？",
            sure = "删除",
            onSure = {
                getViewModel()
                    .request(
                        requestUrl = BaseUrl.mngCouponDel,
                        params = arrayOf("id" to itemId),
                        onSuccess = {
                            showToast("优惠券删除成功！")

                            mList.removeAt(index - 1)
                            mAdapter.apply {
                                notifyItemRemoved(index)
                                notifyItemRangeChanged(index, itemCount - index)
                            }

                            mBinding.listLayout
                                .emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                    )
            }
        )
    }

    /**
     * 优惠券列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .couponList(
                page = index,
                onSuccess = {
                    mList.apply {
                        if (index == 0) {
                            clear()
                            pageNum = 0
                        }
                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}